﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using Ext.Net;
using  Ext.Net.MVC;
using SDSystem.Models;

namespace SDSystem.Controllers
{
    public class DishesController : Controller
    {
        private ForumEntities db=new ForumEntities();

        #region Dishes

        public ActionResult Index()
        {
            return View();
        }

        //Search Forum
        public ActionResult Search()
        {
            var store = X.GetCmp<Store>("DishesDataStore");
            Session["sDishesName"] = X.GetCmp<TextField>("txtDishesName").Text;
            Session["sDishesDescription"] = X.GetCmp<TextField>("txtDishesDescription").Text;
            Session["sGroupDishesName"] = X.GetCmp<TextField>("txtGroupDishesName").Text;
            store.Reload();
            return this.Direct();
        }

        public ActionResult ClearSearch()
        {
            var store = X.GetCmp<Store>("DishesDataStore");
            // Clear search here
            Session["sDishesName"] = X.GetCmp<TextField>("txtDishesName").Text = "";
            Session["sDishesDescription"] = X.GetCmp<TextField>("txtDishesDescription").Text = "";
            Session["sGroupDishesName"] = X.GetCmp<TextField>("txtGroupDishesName").Text="";
            store.Reload();
            return this.Direct();
        }

        //Create Dishes
        public ActionResult Create()
        {
            var query = db.GroupDishes.Select(c => new { c.GroupDishesId, c.GroupName });
            ViewBag.ListGroupDishes = new SelectList(query.AsEnumerable(), "GroupDishesId", "GroupName");
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Dish dh,FormCollection c)
        {
            if (c["btnCreate"] != null)
            {
                if (ModelState.IsValid)
                {
                    string group = Request.Form["ListGroupDishes"];
                    dh.GroupDishes = Convert.ToInt32(group);
                    db.Dishes.AddObject(dh);
                    db.SaveChanges();
                    return this.FormPanel();
                }
                return this.FormPanel();
            }
            else if(c["btnPreview"]!=null)
            {
                return this.RedirectToAction("Index");
            }
            else
            {
                return this.HttpNotFound();
            }
        }

        //Edit Dishes
        public ActionResult Edit(int id)
        {
            var query = db.GroupDishes.Select(c => new { c.GroupDishesId, c.GroupName });
            ViewBag.ListGroupDishes = new SelectList(query.AsEnumerable(), "GroupDishesId", "GroupName");
            Dish dh = db.Dishes.SingleOrDefault(e => e.DishesId == id);
            return View(dh);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Dish dh)
        {
            Dish dh1 = db.Dishes.SingleOrDefault(e => e.DishesId == dh.DishesId);
            if (ModelState.IsValid)
            {
                db.Dishes.Detach(dh1);
                db.Dishes.Attach(dh);
                db.ObjectStateManager.ChangeObjectState(dh, EntityState.Modified);
                db.SaveChanges();
                return this.FormPanel();
            }
            return this.FormPanel();
        }

        //Dishes Data
        public ActionResult DishesData(StoreRequestParameters parameters)
        {
            string dishesname = (String)Session["sDishesName"];
            string dishesdescription = (String) Session["sDishesDescription"];
            String groupdishesname = (String) Session["sGroupDishesName"];
            var result = (from dishesDB in db.Dishes
                         join gdishesDB in db.GroupDishes on dishesDB.GroupDishes equals gdishesDB.GroupDishesId
                         select new
                                    {
                                        dishesDB.DishesId,
                                        dishesDB.Name,
                                        dishesDB.Description,
                                        gdishesDB.GroupName
                                    }).Where(e => (string.IsNullOrEmpty(dishesname) || e.Name.Contains(dishesname)) &&
                                                  (string.IsNullOrEmpty(dishesdescription) || e.Description.Contains(dishesdescription)) &&
                                                  (string.IsNullOrEmpty(groupdishesname) || e.GroupName.Contains(groupdishesname)));

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result =
                    result.OrderBy(parameters.SimpleSort +
                                   (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.DishesId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());
        }

        #endregion

        #region GroupDishes

        public ActionResult ListGroupDishes()
        {
            return View();
        }

        //Create GroupDishes
        public  ActionResult CreateGroupDishes()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateGroupDishes(GroupDish gd)
        {
            if (ModelState.IsValid)
            {
                var httpPostedFileBase = Request.Files[0];
                if (httpPostedFileBase != null)
                {
                    httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//Upload//" + httpPostedFileBase.FileName);
                    gd.Image = "/Content/Upload/" + httpPostedFileBase.FileName;
                }
                gd.IsActive = true;
                db.GroupDishes.AddObject(gd);
                db.SaveChanges();
                X.Msg.Notify("Successfull", "GroupDishes is saved").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Failed", "No GroupDishes is created");
            return this.FormPanel();
        }

        //Edit GroupDishes
        public ActionResult EditGroupDishes(int id)
        {
            GroupDish gh = db.GroupDishes.SingleOrDefault(e => e.GroupDishesId == id);
            Session["sGroupDishesImage"]=ViewBag.GroupDishesImage = gh.Image;
            return View(gh);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditGroupDishes(GroupDish gd)
        {
            GroupDish gd1 = db.GroupDishes.SingleOrDefault(e => e.GroupDishesId == gd.GroupDishesId);
            if(ModelState.IsValid)
            {
                var httpPostedFileBase = Request.Files[0];
                if (httpPostedFileBase != null && httpPostedFileBase.FileName!="")
                {
                    httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//Upload//" + httpPostedFileBase.FileName);
                    gd.Image = "/Content/Upload/" + httpPostedFileBase.FileName;
                }
                else
                {
                    gd.Image = Convert.ToString(Session["sGroupDishesImage"]);
                }
                db.GroupDishes.Detach(gd1);
                db.GroupDishes.Attach(gd);
                db.ObjectStateManager.ChangeObjectState(gd, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Successfull", "GroupDishes is saved").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Failed", "No GroupDishes is saved");
            return this.FormPanel();
        }

        //GroupDishes Data
        public ActionResult GroupDishesData(StoreRequestParameters parameters)
        {
            var result = from gdishesDB in db.GroupDishes
                         select new
                                    {
                                        gdishesDB.GroupDishesId,
                                        gdishesDB.GroupName,
                                        gdishesDB.Image,
                                        gdishesDB.Description,
                                        gdishesDB.IsActive
                                    };

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result =
                    result.OrderBy(parameters.SimpleSort +
                                   (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.GroupDishesId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData, result.Count());


        }

        #endregion


    }
}
